//
//  DestinationAndMapViewController.m
//  OCUI
//
//  Created by login on 15-8-6.
//
//

#import "DestinationAndMapViewController.h"
#import <BaiduMapAPI/BMapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "HttpClient.h"
@interface DestinationAndMapViewController ()<UISearchBarDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,HttpClientDelegate>
{
    UITableView *detinationAndMapTableView;
    NSArray *detinationAndMapDataArray;
    UITableView *baiduSearchTableView;
    NSArray *baiduSearchDataArray;
    UISearchBar *searchDestination;
    BMKMapView* _mapView;
    BMKLocationService *_locService;
    CLLocationManager *myLocationManager;
    
    NSUserDefaults *userDefaults;
}
@end

@implementation DestinationAndMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    userDefaults = [NSUserDefaults standardUserDefaults];
    [self initView];
}

- (void)initData
{
    NSArray *defaultArray = [userDefaults objectForKey:@"searchHistory"];
    
    if (defaultArray.count != 0) {
        detinationAndMapDataArray = [userDefaults objectForKey:@"searchHistory"];
    }
 
}

- (void)initView
{
    searchDestination = [[UISearchBar alloc]initWithFrame:CGRectMake(30, 64, self.view.frame.size.width-60, 40)];
    searchDestination.placeholder = @"请输入出发地点";
    searchDestination.delegate = self;
    [searchDestination setTintColor:[UIColor blackColor]];
    searchDestination.searchBarStyle = UISearchBarStyleMinimal;
    [self.view addSubview:searchDestination];
    
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, self.view.frame.size.height/3)];
    _mapView.delegate = self;
    _mapView.mapType = BMKMapTypeStandard;
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    [_mapView setShowsUserLocation:YES];
    _mapView.isSelectedAnnotationViewFront = YES;
    _mapView.showsUserLocation = YES;//显示定位图层
    [self.view addSubview:_mapView];
    
    _locService = [[BMKLocationService alloc]init];
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100];
    //初始化BMKLocationService
    _locService.delegate = self;

    if (myLocationManager) {
        myLocationManager=nil;
        myLocationManager.delegate=nil;
    }
    myLocationManager=[[CLLocationManager alloc]init];
    myLocationManager.desiredAccuracy=kCLLocationAccuracyBest;
    myLocationManager.delegate=self;
    if ([[[UIDevice currentDevice] systemVersion]floatValue]>=8.0) {
        [myLocationManager requestAlwaysAuthorization];
    }
    [myLocationManager startUpdatingLocation];
    
    detinationAndMapTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height/3 + 104, self.view.frame.size.width, self.view.frame.size.height*2/3 - 104)];
    detinationAndMapTableView.delegate = self;
    detinationAndMapTableView.dataSource = self;
    detinationAndMapTableView.tag = DetinationAndMapTag;
    [self.view addSubview:detinationAndMapTableView];
    
    baiduSearchTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, self.view.frame.size.height - 104)];
    baiduSearchTableView.delegate = self;
    baiduSearchTableView.dataSource = self;
    baiduSearchTableView.hidden = YES;
    baiduSearchTableView.tag = BaiduSearchTag;
    [self.view addSubview:baiduSearchTableView];
    
}
#pragma mark - 地理编码
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [myLocationManager stopUpdatingLocation];

    NSLog(@"location ok location ok location ok location ok");
    
    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSLog(@"%@", [test objectForKey:@"State"]);
            
            [self performSelectorOnMainThread:@selector(updateMain:) withObject:test waitUntilDone:YES];
        }
    }];
    
}

- (void)updateMain:(NSDictionary *)dic
{
    NSLog(@"%@",dic);
    NSLog(@"1111%@",dic[@"City"]);
    NSLog(@"1111%@",dic[@"Country"]);
    NSLog(@"1111%@",dic[@"FormattedAddressLines"][0]);
    NSLog(@"1111%@",dic[@"Name"]);
    NSLog(@"1111%@",dic[@"State"]);
    NSLog(@"1111%@",dic[@"Street"]);
    NSLog(@"1111%@",dic[@"SubLocality"]);
    NSLog(@"1111%@",dic[@"Thoroughfare"]);

    UITableViewCell *cell = (UITableViewCell *)[self.view viewWithTag:4567];
    cell.textLabel.text = [NSString stringWithFormat:@"[当前]%@%@%@",dic[@"State"],dic[@"Street"],dic[@"State"]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@",dic[@"State"],dic[@"SubLocality"]];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
#pragma mark - MapDelegate
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
    NSLog(@"地图加载成功");
    
    //启动LocationService
    [_locService startUserLocationService];
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    _mapView.centerCoordinate = userLocation.location.coordinate;
    [_mapView updateLocationData:userLocation];
    
    [_locService stopUserLocationService];
    //    _mapView.showsUserLocation = NO;
    [self changeMapCenter];
    
}

- (void)changeMapCenter
{
    [_locService stopUserLocationService];

    BMKCoordinateRegion  region;
    region.center = _mapView.centerCoordinate;//中心点
    region.span.latitudeDelta = 0.005;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
    region.span.longitudeDelta = 0.005;//纬度范围
    [_mapView setRegion:region animated:YES];
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == DetinationAndMapTag)
    {
        return detinationAndMapDataArray.count + 1;
    }else {
        return baiduSearchDataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == DetinationAndMapTag) {
        static NSString *cellIdentifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        }
        [myLocationManager startUpdatingLocation];
        
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"[当前]%@",@"正在定位"];
            cell.detailTextLabel.text = @"";
            cell.tag = 4567;
        }else
        {
            cell.textLabel.text = @"eqw";
        }
        return cell;

    }else{
        static NSString *cellID = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        }
        if (baiduSearchDataArray.count != 0) {
            cell.textLabel.text = baiduSearchDataArray[indexPath.row][@"name"];
            NSString *city = baiduSearchDataArray[indexPath.row][@"city"];
            NSString *district = baiduSearchDataArray[indexPath.row][@"district"];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@",city,district];
        }else
        {
            baiduSearchTableView.hidden = YES;
        }
        return cell;
    }
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{

    [searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        baiduSearchTableView.hidden = YES;
        _mapView.hidden = NO;
        detinationAndMapTableView.hidden = NO;

    }else
    {
        baiduSearchTableView.hidden = NO;
        _mapView.hidden = YES;
        detinationAndMapTableView.hidden = YES;
        
        HttpClient *ii = [[HttpClient alloc]init];
        ii.delegate = self;
        
        NSString *hostString = @"http://192.168.3.62:8901/specialcar/placesuggestion1";
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:@"2" forKey:@"clienttype"];
        [dic setObject:searchText forKey:@"q"];
        [dic setObject:@"北京" forKey:@"region"];
        
        [ii getRequestAsyWithProgress:self.view and:hostString and:dic requestType:GET];
        
    }
    

}
- (void)sendRequestDataArray:(NSDictionary *)dict
{
    baiduSearchDataArray = dict[@"results"];
    [baiduSearchTableView reloadData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.tabBarController.tabBar setHidden:NO];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
